package toy.keli.edic.ui.main.extend

import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString

fun String.commonPrefixLengthWith(other: String): Int {
    var i = 0
    while (i < length && i < other.length && this[i] == other[i]) {
        i++
    }
    return i
}

fun String.convertANSIToUTF8(): String {
    val ansiBytes = this.toByteArray(charset("ISO-8859-1")) // 假设是ANSI编码
    return String(ansiBytes, charset("UTF-8"))
}

fun annotatedText(text:String,searchKey:String,selected:Boolean=false,searchSelectedIndex:Int=0) : AnnotatedString {
    if(searchKey.isEmpty()) return buildAnnotatedString{append(text)}
    return buildAnnotatedString {
        var startIndex = 0
        val lowerText = text.toLowerCase();
        val lowerQuery = searchKey.toLowerCase()
        var selectIndex = 0
        while (startIndex < lowerText.length) {
            // 查找关键词出现的位置
            val queryStart = lowerText.indexOf(lowerQuery, startIndex)

            if (queryStart == -1) {
                // 没有更多匹配，添加剩余文本
                append(text.substring(startIndex))
                break
            }

            // 添加关键词前的普通文本
            if (queryStart > startIndex) {
                append(text.substring(startIndex, queryStart))
            }

            // 添加高亮的关键词
            append(lowerQuery)
            addStyle(
                style = SpanStyle(
                    background = if(selected && selectIndex == searchSelectedIndex) Color.Red else  Color.Yellow
                ),
                start = queryStart,
                end = queryStart+lowerQuery.length
            )
            startIndex = queryStart+lowerQuery.length
            selectIndex++;
        }
    }
}